﻿using System.Collections.Generic;
using UnityEngine;

namespace winS.Unity
{
    /// <summary>
    /// 协程更新器.
    /// 该类负责在Unity帧循环下驱动协程
    /// </summary>
    internal class CoroutineUpdater : MonoBehaviour
    {
        internal readonly List<CoroutineCore> runningList = new List<CoroutineCore>(4);
        internal readonly List<CoroutineCore> waitForAddList = new List<CoroutineCore>(4);
        internal readonly List<CoroutineCore> waitForRemoveList = new List<CoroutineCore>(4);

        private void Update()
        {
            RemoveFromRunningQueue();
            AddToRunningQueue();
            UpdateRunningQueue();
        }

        public void RemoveCoroutineCore(CoroutineCore coroutineCore)
        {
            waitForRemoveList.Add(coroutineCore);
        }
        public void AddCoroutineCore(CoroutineCore coroutineCore)
        {
            //立刻更新新加入的协程
            CoroutineState coroutineState = coroutineCore.Update();
            if (coroutineState is CoroutineState.Completed or CoroutineState.Stopped) return;//一帧就结束了, 什么都不需要做
            waitForAddList.Add(coroutineCore);
        }

        private void AddToRunningQueue()
        {
            foreach (var coroutineCore in waitForAddList) runningList.Add(coroutineCore);
            waitForAddList.Clear();
        }
        private void RemoveFromRunningQueue()
        {
            foreach (var coroutine in waitForRemoveList)
            {
                runningList.Remove(coroutine);
                CoroutineCorePool.Push(coroutine);
            }
            waitForRemoveList.Clear();
        }
        private void UpdateRunningQueue()
        {
            //不要使用foreach, 新加入的协程是立即更新的
            for (int i = 0; i < runningList.Count; i++) runningList[i].Update();
        }
    }
}